﻿using RXY_Mall.Core;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services.Shop.Dto;
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace RXY_Mall.Services.Shop
{
    public class ShopService : IShopService
    {
        private RXY_MallContext db;

        public ShopService()
        {
            db = new RXY_MallContext();
        }

        /// <summary>
        /// 添加店铺
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseService<bool>> AddShop(AddShopsInput input)
        {
            ResponseService<bool> result = new ResponseService<bool>();
            result.code = 0;
            try
            {
                var companys = await db.gw_companys.ToListAsync();
                foreach (var item in input.shops)
                {
                    var company = companys.FirstOrDefault(c => c.api_company_id == item.api_company_id);

                    if (company == null)
                    {
                        result.msg = "公司不存在";
                        return result;
                    }

                    var shop = await db.gw_shops.FirstOrDefaultAsync(c => c.api_shop_id == item.api_shop_id);
                    if (shop != null)
                    {
                        result.msg = "店铺已添加";
                        return result;
                    }

                    shop = new gw_shop()
                    {
                        api_shop_id = item.api_shop_id,
                        api_server_id = item.api_server_id,
                        name = item.shop_name,

                        add_time = DateTime.Now,
                        address = item.address,
                        area = item.area,
                        province_code = item.province_code,
                        city_code = item.city_code,
                        country_code = item.country_code,
                        company_id = company.id,
                        logo = "",

                        mobile = item.contacts_phone,
                        mangername = item.contacts_name,
                        mangermobile = item.contacts_phone,
                        type = item.shop_type,
                        status = 1,
                    };

                    db.gw_shops.Add(shop);
                }

                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "添加成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;
        }
    }
}
